package fr.vincent7894.feedroid.feed.task.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;

import org.xmlpull.v1.XmlPullParser;

import android.app.ProgressDialog;
import fr.vincent7894.feedroid.feed.context.impl.RssFeedContext;
import fr.vincent7894.feedroid.feed.pojo.Feed;
import fr.vincent7894.feedroid.feed.pojo.FeedAlias;
import fr.vincent7894.feedroid.feed.pojo.impl.RssFeed;
import fr.vincent7894.feedroid.feed.task.AbstractProgressDialogFeedTask;
import fr.vincent7894.feedroid.utils.NetworkUtils;
import fr.vincent7894.feedroid.utils.XmlPullParserFactoryUtils;

public class RssFeedTask extends AbstractProgressDialogFeedTask {

	public RssFeedTask(ProgressDialog view) {
		super(view);
	}

	@Override
	protected Collection<Feed> doInBackground(FeedAlias... params) {
		FeedAlias alias = params[0];
		Collection<Feed> feeds = new ArrayList<Feed>();

		if (!(alias.getFeedContext() instanceof RssFeedContext)) {
			super.setLastError("Bad context");
			super.cancel(true);
			return null;
		}

		InputStream inputStream = null;
		try {
			inputStream = NetworkUtils.httpGet(alias.getUri());
		} catch (Exception e) {
			e.printStackTrace();
			super.setLastError(e.getMessage());
			super.cancel(true);
			return null;
		}

		XmlPullParser parser = null;
		try {
			parser = XmlPullParserFactoryUtils.newParser();

			parser.setInput(inputStream, "UTF-8");

			RssFeed feed = null;
			boolean hasFeed = false;
			while (parser.next() != XmlPullParser.END_DOCUMENT) {
				if (parser.getEventType() == XmlPullParser.START_TAG) {
					if (parser.getName().equals("item")) {
						feed = new RssFeed();
						hasFeed = true;
					}

					if (hasFeed) {
						if (parser.getName().equals("title")) {
							feed.setTitle(this.getText(parser));
						} else if (parser.getName().equals("content")) {
							feed.setContent(this.getText(parser));
						} else if (parser.getName().equals("description")) {
							feed.setDescription(this.getText(parser));
						} else if (parser.getName().equals("link")) {
							feed.setLink(this.getText(parser));
						} else if (parser.getName().equals("pubDate")) {
							feed.setPubDate(this.getText(parser));
						}
					}
				} else if (parser.getEventType() == XmlPullParser.END_TAG
						&& parser.getName().equals("item")) {
					feeds.add(feed);
					hasFeed = false;
				}
			}

			super.publishProgress(100);
		} catch (Exception e) {
			e.printStackTrace();
			super.setLastError(e.getMessage());
			super.cancel(true);
			return null;
		}

		return feeds;
	}

	private String getText(XmlPullParser parser) throws Exception {
		String txt = "";

		if (parser.next() == XmlPullParser.TEXT) {
			txt = parser.getText();
			parser.nextTag();
		}

		return txt;
	}
}
